// 微信订阅消息推送工具函数
const axios = require('axios');

// 数据库连接池（由外部传入）
let dbPool = null;

// 设置数据库连接池
function setDatabasePool(pool) {
    dbPool = pool;
}

// 微信小程序配置缓存
let wechatConfigCache = {
    appId: '',
    appSecret: '',
    templates: {
        wechat_template_loan_apply: '',
        wechat_template_loan_approve: '',
        wechat_template_loan_reminder: '',
        wechat_template_repair_submit: '',
        wechat_template_repair_accept: '',
        wechat_template_repair_complete: '',
        wechat_template_admin_repair_notify: ''  // 管理员通知模板
    },
    lastUpdate: 0
};

// 从数据库获取微信配置（带缓存，5分钟更新一次）
async function getWeChatConfig() {
    const now = Date.now();
    // 如果缓存有效（5分钟内），直接返回
    if (wechatConfigCache.lastUpdate && (now - wechatConfigCache.lastUpdate < 5 * 60 * 1000)) {
        return wechatConfigCache;
    }

    try {
        if (!dbPool) {
            throw new Error('数据库连接池未初始化，请先调用 setDatabasePool()');
        }

        const [rows] = await dbPool.execute(
            "SELECT config_key, config_value FROM system_config WHERE config_group = 'wechat'"
        );

        rows.forEach(row => {
            if (row.config_key === 'wechat_app_id') {
                wechatConfigCache.appId = row.config_value;
            } else if (row.config_key === 'wechat_app_secret') {
                wechatConfigCache.appSecret = row.config_value;
            } else if (wechatConfigCache.templates.hasOwnProperty(row.config_key)) {
                wechatConfigCache.templates[row.config_key] = row.config_value || '';
            } else if (row.config_key.endsWith('_content')) {
                // Store JSON string for template content (e.g., wechat_template_repair_submit_content)
                wechatConfigCache.templateContent = wechatConfigCache.templateContent || {};
                wechatConfigCache.templateContent[row.config_key] = row.config_value || '';
            }
        });
        wechatConfigCache.lastUpdate = now;

        return wechatConfigCache;
    } catch (error) {
        console.error('获取微信配置失败:', error);
        return wechatConfigCache;
    }
}

// 获取access_token（带缓存）
let accessTokenCache = {
    token: '',
    expireTime: 0
};

async function getAccessToken() {
    // 如果缓存有效，直接返回
    if (accessTokenCache.token && Date.now() < accessTokenCache.expireTime) {
        return accessTokenCache.token;
    }

    const config = await getWeChatConfig();
    if (!config.appId || !config.appSecret) {
        console.error('未配置微信AppID或AppSecret');
        return null;
    }

    try {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appId}&secret=${config.appSecret}`;
        const response = await axios.get(url);

        if (response.data.access_token) {
            accessTokenCache.token = response.data.access_token;
            // 提前5分钟过期
            accessTokenCache.expireTime = Date.now() + (response.data.expires_in - 300) * 1000;
            return accessTokenCache.token;
        } else {
            console.error('获取access_token失败:', response.data);
            return null;
        }
    } catch (error) {
        console.error('获取access_token异常:', error);
        return null;
    }
}

// 发送订阅消息
async function sendSubscribeMessage(openid, templateId, data, page) {
    try {
        const accessToken = await getAccessToken();
        if (!accessToken) {
            console.error('无法获取access_token');
            return false;
        }

        const url = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`;
        const requestData = {
            touser: openid,
            template_id: templateId,
            page: page || 'pages/index/index',
            data: data,
            miniprogram_state: 'formal' // formal正式版, trial体验版, developer开发版
        };

        const response = await axios.post(url, requestData);

        if (response.data.errcode === 0) {
            console.log(`订阅消息发送成功: ${openid}`);
            return true;
        } else {
            console.error(`订阅消息发送失败: ${response.data.errmsg}`);
            return false;
        }
    } catch (error) {
        console.error('发送订阅消息异常:', error);
        return false;
    }
}

// 借用申请成功通知
async function sendLoanApplyNotice(openid, assetName, expectedReturnDate) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_loan_apply;
    if (!templateId) {
        console.log('借用申请通知模板ID未配置');
        return false;
    }

    const data = {
        thing1: { value: assetName.substring(0, 20) }, // 资产名称
        date2: { value: expectedReturnDate }, // 预计归还日期
        thing3: { value: '您的借用申请已提交，请等待审批' }
    };

    return await sendSubscribeMessage(openid, templateId, data, 'pages/my-loans/my-loans');
}

// 审批结果通知
async function sendLoanApproveNotice(openid, assetName, approved, rejectReason) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_loan_approve;
    if (!templateId) {
        console.log('审批结果通知模板ID未配置');
        return false;
    }

    const data = {
        thing1: { value: assetName.substring(0, 20) }, // 资产名称
        phrase2: { value: approved ? '审批通过' : '审批拒绝' }, // 审批结果
        thing3: { value: approved ? '请按时归还' : (rejectReason || '未通过审批').substring(0, 20) }
    };

    return await sendSubscribeMessage(openid, templateId, data, 'pages/my-loans/my-loans');
}

// 归还提醒通知
async function sendReturnReminder(openid, assetName, expectedReturnDate) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_loan_reminder;
    if (!templateId) {
        console.log('归还提醒通知模板ID未配置');
        return false;
    }

    const data = {
        thing1: { value: assetName.substring(0, 20) }, // 资产名称
        date2: { value: expectedReturnDate }, // 归还日期
        thing3: { value: '请及时归还资产，避免逾期' }
    };

    return await sendSubscribeMessage(openid, templateId, data, 'pages/my-loans/my-loans');
}

// 报修成功通知
async function sendRepairSubmitNotice(openid, labName, faultType, orderId) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_repair_submit;
    if (!templateId) {
        console.log('报修成功通知模板ID未配置');
        return false;
    }

    // Load optional JSON content configured in admin panel
    const extraJson = config.templateContent?.wechat_template_repair_submit_content || '';
    const extra = extraJson ? JSON.parse(extraJson) : {};

    const data = {
        thing1: { value: extra.thing1?.value || labName.substring(0, 20) }, // 报修设备（这里使用机房名称作为示例）
        thing3: { value: extra.thing3?.value || faultType.substring(0, 20) }, // 处理人员（这里使用故障类型示例）
        time4: { value: extra.time4?.value || new Date().toISOString().slice(0, 16).replace('T', ' ') }, // 完成时间或当前时间
        thing5: { value: extra.thing5?.value || '您的报修已提交，请等待技术员处理' }
    };

    return await sendSubscribeMessage(openid, templateId, data,
        `pages/order-detail/order-detail?orderId=${orderId}`);
}

// 维修接单通知
async function sendRepairAcceptNotice(openid, labName, technicianName, orderId) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_repair_accept;
    if (!templateId) {
        console.log('维修接单通知模板ID未配置');
        return false;
    }

    // Load optional JSON content configured in admin panel
    const extraJson = config.templateContent?.wechat_template_repair_accept_content || '';
    const extra = extraJson ? JSON.parse(extraJson) : {};

    const data = {
        thing1: { value: extra.thing1?.value || labName.substring(0, 20) }, // 机房名称
        thing3: { value: extra.thing3?.value || technicianName.substring(0, 20) }, // 处理人员（技术员）
        time4: { value: extra.time4?.value || new Date().toISOString().slice(0, 16) }, // 接单时间或当前时间
        thing5: { value: extra.thing5?.value || '技术员已接单，正在处理中' }
    };

    return await sendSubscribeMessage(openid, templateId, data, `pages/order-detail/order-detail?orderId=${orderId}`);
}

// 维修完成通知
async function sendRepairCompleteNotice(openid, labName, solution, orderId) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_repair_complete;
    if (!templateId) {
        console.log('维修完成通知模板ID未配置');
        return false;
    }

    // Load optional JSON content configured in admin panel
    const extraJson = config.templateContent?.wechat_template_repair_complete_content || '';
    const extra = extraJson ? JSON.parse(extraJson) : {};

    const data = {
        thing1: { value: extra.thing1?.value || labName.substring(0, 20) }, // 机房名称
        thing3: { value: extra.thing3?.value || (solution ? solution.substring(0, 20) : '维修完成') }, // 处理方案或结果
        time4: { value: extra.time4?.value || new Date().toISOString().slice(0, 16).replace('T', ' ') }, // 完成时间或当前时间
        thing5: { value: extra.thing5?.value || '感谢您的使用！' }
    };

    return await sendSubscribeMessage(openid, templateId, data, `pages/order-detail/order-detail?orderId=${orderId}`);
}

// 管理员报修通知（用户提交报修后推送给管理员）
async function sendAdminRepairNotify(adminOpenid, orderId, userName, submitTime, deviceInfo, faultDescription) {
    const config = await getWeChatConfig();
    const templateId = config.templates.wechat_template_admin_repair_notify;
    if (!templateId) {
        console.log('管理员报修通知模板ID未配置');
        return false;
    }

    // Load optional JSON content configured in admin panel
    const extraJson = config.templateContent?.wechat_template_admin_repair_notify_content || '';
    const extra = extraJson ? JSON.parse(extraJson) : {};

    const data = {
        character_string1: { value: extra.character_string1?.value || String(orderId) }, // 单号（工单ID）
        thing2: { value: extra.thing2?.value || userName.substring(0, 20) }, // 申请人
        time3: { value: extra.time3?.value || submitTime }, // 申请时间
        thing4: { value: extra.thing4?.value || deviceInfo.substring(0, 20) }, // 设备信息
        thing5: { value: extra.thing5?.value || faultDescription.substring(0, 20) } // 故障描述
    };

    console.log('发送管理员报修通知:', { adminOpenid, orderId, templateId });
    return await sendSubscribeMessage(adminOpenid, templateId, data, `pages/order-detail/order-detail?orderId=${orderId}`);
}

// 获取小程序码（无限数量，圆形）
async function getUnlimitedQRCode(scene, page, width = 430) {
    try {
        const accessToken = await getAccessToken();
        if (!accessToken) {
            console.error('无法获取access_token');
            return null;
        }

        const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
        const requestData = {
            scene: scene,
            page: page || 'pages/index/index',
            width: width,
            check_path: false, // 开发阶段设为false，避免因页面未发布而报错
            env_version: 'develop' // develop开发版, trial体验版, release正式版
        };

        const response = await axios.post(url, requestData, {
            responseType: 'arraybuffer' // 获取二进制图片数据
        });

        if (response.headers['content-type'].includes('application/json')) {
            // 如果返回的是JSON，说明出错了
            const error = JSON.parse(response.data.toString());
            console.error('获取小程序码失败:', error);
            return null;
        }

        return response.data;
    } catch (error) {
        console.error('获取小程序码异常:', error);
        return null;
    }
}

module.exports = {
    setDatabasePool,  // 新增：设置数据库连接池
    sendLoanApplyNotice,
    sendLoanApproveNotice,
    sendReturnReminder,
    sendRepairSubmitNotice,
    sendRepairAcceptNotice,
    sendRepairCompleteNotice,
    sendAdminRepairNotify,  // 新增管理员通知
    getUnlimitedQRCode,
    // expose cache clear for admin UI
    clearWeChatCache: () => {
        wechatConfigCache.lastUpdate = 0;
        accessTokenCache.token = '';
        accessTokenCache.expireTime = 0;
    }
};
